const RedisClient = require('../../util/redis');
const logger = require('../../util/logger');
const config = require('../../config');
const Store = require('./store');

class RedisStore extends Store {
  
  constructor(options = {}) {
    super(false);
    if (!options.client) {
      this.client = new RedisClient(options.redisOpt).origin();
    } else {
      this.client = options.client;
    }
    this.namespace = config.server.name + ':' + options.prefix + ':';
  }
  
  async get(sid) {
    let data = await this.client.get(this.namespace + sid);
    logger.debug('get session: %s', data || 'none');
    if (!data) return null;
    try {
      return JSON.parse(data);
    } catch (err) {
      logger.error('parse session error: %s', err.message);
    }
  }
  
  async set(sid, session) {
    let ttl = session.cookie.maxAge;
    if (typeof ttl === 'number') {
      ttl = Math.ceil(ttl / 1000);
    }
    session = JSON.stringify(session);
    if (ttl) {
      logger.debug('setex %s %s %s', sid, ttl, session);
      await this.client.setex(this.namespace + sid, ttl, session);
    } else {
      logger.debug('set %s %s', sid, session);
      await this.client.set(this.namespace + sid, session);
    }
  }
  
  async destroy(sid) {
    logger.debug('del %s', sid);
    await this.client.del(this.namespace + sid);
  }
}

module.exports = RedisStore;
